import React, {useEffect} from 'react';
import {
    Box,
    Button,
    Card,
    CardContent,
    Dialog,
    Divider,
    FormControl,
    IconButton,
    InputLabel,
    MenuItem,
    Select,
    TextField,
    Typography
} from "@mui/material";
import {Done, RestartAlt} from "@mui/icons-material";
import LoadingButton from "@mui/lab/LoadingButton";
import CircularProgress from "@mui/material/CircularProgress";
import DialogTitle from "@mui/material/DialogTitle";
import CloseIcon from "@mui/icons-material/Close";

import {save} from "../../api/school/class-group";
import {alert} from "../common/alert";
import {list as listClassrooms} from "../../api/info/classroom";
import {valid} from "../../api/info/course";


const defaultForm = {
    id: 0,
    schoolId: 0,
    completedLessons: 0,
    nextLessonNumber: 1,
    status: 'ACTIVE',
    /*---- form data ----*/
    name: '',
    courseId: 0,
    classroomId: 0,
    studentIds: [],
};
Object.freeze(defaultForm);

function CreateClassGroup({open, onClose}) {

    const [classrooms, setClassrooms] = React.useState([]);

    const [form, setForm] = React.useState({...defaultForm});
    const [submitting, setSubmitting] = React.useState(false);

    const [courses, setCourses] = React.useState([]);

    const [students, setStudents] = React.useState([]);

    useEffect(() => {
        listClassrooms().then(data => {
            setClassrooms(data);
        });
    }, []);

    useEffect(() => {
        if (open) {
            valid().then(data => {
                setCourses(data);
            });
        }
    }, [open]);

    const handleChange = (event) => {
        const {name, value} = event.target;

        if (name === 'courseId') {
            const course = courses.find(e => e.id === value);
            setForm({...form, [name]: value});
            setStudents(course.ungroupedStudents);
        } else if (name === 'studentIds') {
            const classroom = classrooms.find(e => e.id === form.classroomId);
            if (value.length > classroom.capacity) {
                alert(`教室 【${classroom.name}】 只有 ${classroom.capacity} 个座位，不能添加更多学员了`, 'error');
            } else {
                setForm({...form, [name]: value});
            }
        } else {
            setForm({...form, [name]: value});
        }
    }

    const handleSubmit = (event) => {
        event.preventDefault();

        setSubmitting(true);
        save(form).then((data) => {
            setSubmitting(false);

            if (data) {
                // remove grouped students from ungrouped list
                const newCourse = courses.map(e => e.id === form.courseId ? {
                        ...e,
                        ungroupedStudents: e.ungroupedStudents.filter(s => !form.studentIds.includes(s.id))
                    } : e
                ).filter(e => e.ungroupedStudents.length > 0);

                setCourses(newCourse);
                setForm({...defaultForm});

                alert('班级创建成功');
            }
        });
    }

    function handleClose(event, reason) {
        event.stopPropagation();
        if (reason !== 'backdropClick' && reason !== 'escapeKeyDown') {
            onClose();
        }
    }

    return (
        <Dialog open={open} onClose={handleClose}>
            <DialogTitle sx={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
                <Typography variant="title">新增班级</Typography>
                <IconButton onClick={onClose}><CloseIcon/></IconButton>
            </DialogTitle>

            <Card raised sx={{width: '480px', padding: 3, boxSizing: 'border-box'}}>
                <CardContent>
                    <form onSubmit={handleSubmit}>
                        <Box display="flex" flexDirection="column" gap={2}>

                            <TextField label="班级名称" name="name" value={form.name} onChange={handleChange}
                                       autoComplete={"off"} required autoFocus/>

                            <FormControl fullWidth>
                                <InputLabel>课程</InputLabel>
                                <Select value={form.courseId} label="课程" name="courseId" onChange={handleChange}>
                                    <MenuItem value={0} disabled={true}>选择课程</MenuItem>
                                    <Divider/>
                                    {courses.map(e => <MenuItem key={e.id} value={e.id}>{e.name}</MenuItem>)}
                                </Select>
                            </FormControl>

                            <FormControl fullWidth>
                                <InputLabel>教室</InputLabel>
                                <Select value={form.classroomId} label="教室" name="classroomId"
                                        onChange={handleChange}>
                                    <MenuItem value={0} disabled={true}>选择教室</MenuItem>
                                    <Divider/>
                                    {classrooms.filter(e => e.capacity > 0).map(e =>
                                        <MenuItem key={e.id} value={e.id}>{e.name} ({e.capacity}座)</MenuItem>)}
                                </Select>
                            </FormControl>

                            <FormControl fullWidth disabled={students.length === 0 || form.classroomId === 0}>
                                <InputLabel>学员</InputLabel>
                                <Select value={form.studentIds} label="学员" name="studentIds" multiple
                                        onChange={handleChange}>
                                    <MenuItem value={0} disabled={true}>选择学员，可多选</MenuItem>
                                    {students.map(e => <MenuItem key={e.id} value={e.id}>{e.name}</MenuItem>)}
                                </Select>
                            </FormControl>

                            <Box>
                                <Button
                                    variant="contained"
                                    color="primary"
                                    startIcon={<RestartAlt/>}
                                    sx={{marginTop: "16px", mr: 2}}
                                    onClick={() => setForm({...defaultForm})}
                                > 清空
                                </Button>

                                <LoadingButton
                                    type="submit"
                                    disabled={submitting || form.name === '' || form.courseId === 0 || form.classroomId === 0 || form.studentIds.length === 0}
                                    variant="contained"
                                    color="primary"
                                    startIcon={<Done/>}
                                    sx={{marginTop: "16px"}}
                                    loadingIndicator={<CircularProgress color="inherit" size={24}/>}
                                    loading={submitting}
                                >
                                    提交
                                </LoadingButton>
                            </Box>
                        </Box>
                    </form>
                </CardContent>
            </Card>
        </Dialog>
    );
}

export default CreateClassGroup;
